<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="产品">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请选择产品"
            clearable
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="resetMaterial"> 清除 </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="beforeGetTableList">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="primary" @click="coreBasicImport">导入 </el-button>
        <el-button
          @click="
            useDownload(
              '/mes/mesironconfiginfo/exportTemp',
              '冷铁配置信息上传模板',
              searchParam,
              true,
              '.xls'
            )
          "
        >
          导入模板下载
        </el-button>
        <el-button
          class="ml-3"
          @click="
            useDownload(
              '/mes/mesironconfiginfo/export',
              '冷铁配置信息',
              searchParam,
              true,
              '.xls'
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        element-loading-text="数据准备中，请稍后..."
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
        @sort-change="onTableSortChanged"
        class="dataTable"
      >
<!--        <el-table-column type="selection" width="55" align="center"/>-->
        <el-table-column width="70" label="序号" align="center" fixed>
          <template #default="{ $index, row }">
            <span v-if="row.id !== '-999'">{{ $index + 1 }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          label="产品名称"
          prop="materialName"
          width="240"
          show-overflow-tooltip
          fixed
          align="left"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span v-if="row.id != -999" class="container">
              <!--@click="planMaterial(row)"-->
              {{ row.materialName }}
            </span>
            <span class="text-[13px]" v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in intervalDayList"
          :key="index"
          :label="`${item.name}`"
          min-width="65"
          align="right"
        >
          <template #default="{ row, data = getListData(row, item) }">
            <div class="padding012" style="height: 30px">
              {{ data }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 导入 -->
    <ImportExcel ref="coreBasicImportRef" />
    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table ref="uploadErrorRef" :errorDataList="errorDataList" />

    <!--物料选择-->
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
  </div>
</template>

<script setup lang="ts">
import { filterOrder, promptValidateNumber } from "@/utils/commonHooks";
import request from "@/utils/request";
import { useDownload } from "@/utils/useTable";

defineOptions({
  name: "MESMESCOREDEMANDTOTAL",
  inheritAttrs: false,
});

// 初始化搜索参数数据
const searchParam = reactive<any>({
  materialId: "",
  materialCode: "",
});

// 点击搜索按钮后被保存的搜索数据
const searchedParam = reactive<any>({
  materialId: "",
  materialCode: "",
});

// 搜索时间变化后处理函数
const intervalDayList = ref<any[]>([]);

// 行复选框选中后处理
const ids = ref<string[]>([]);
const dataTableRef = ref();
// 表格选择
const totalMultipleSelection: any = ref([]);
function handleSelectionChange(selection: TableResultObject[]) {
  ids.value = selection.map((item: TableResultObject) => item.id);
  totalMultipleSelection.value = selection;
}

// 开始展示逻辑处理
const loading = ref(false);
const tableData = ref([]);
// 点击展示之前
function beforeGetTableList() {
  getTableList(1);
}
function reset() {
  Object.assign(searchParam, {
    materialId: "",
    materialCode: "",
    yearMonthPlan: "",
  });
  getTableList(1);
}
// 点击展示之后
async function getTableList(isReset = 0) {
  // isReset为 1 加载刷新、0 无感知刷新
  if (isReset === 1) {
    dataTableRef.value.setScrollTop(0);
    loading.value = true;
  }
  const { data }: any = await request({
    url: "/mes/mesironconfiginfo/queryByList",
    method: "post",
    data: isReset === 0 ? toRaw(searchedParam) : toRaw(searchParam),
  }).catch(() => {});
  // 储存被搜索条件
  Object.assign(searchedParam, {
    ...toRaw(searchParam),
  });
  intervalDayList.value = data.item;
  // 数据处理
  tableData.value = data.data;
  loading.value = false;
}

// 监听表格后台排序方法
const initParam = reactive({ sort: {} });
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };

  getTableList(1);
}

function getMonthAndDay(date: any) {
  let month = date.slice(5, 7);
  let day = date.slice(8, 10);
  return month + "/" + day;
}
//产品选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.materialId = data.id;
    searchParam.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  searchParam.materialId = "";
  searchParam.materialCode = "";
};
onMounted(() => {
  getTableList(1);
});
function getListData(row, item) {
  for (const [key, value] of Object.entries(row)) {
    if (
      item.name == key ||
      (key == "serialNumber" && item.name == "序号") ||
      (key == "materialName" && item.name == "产品名称")
    ) {
      return value;
    }
  }
}
// 导入计划
const uploadApi = "/mes/mesironconfiginfo/upload";
const coreBasicImportRef = ref();
const errorDataList = ref([]);
async function coreBasicImportApiFunc(formdata: FormData, config: any) {
  await request
    .post(uploadApi, formdata, config)
    .then((res: any) => {
      coreBasicImportRef.value.resCode = 0;
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "上传成功！",
        });
      }
    })
    .catch((e) => {
      coreBasicImportRef.value.resCode = 500;
    });
}
const coreBasicImport = () => {
  let params = {
    title: "导入冷铁配置信息",
    tempApi: "", //模板下载
    importApi: coreBasicImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {},
  };
  coreBasicImportRef.value.acceptParams(params);
};
</script>

<style lang="scss" scoped>
// 所有表格样式
:deep(.dataTable) {
  .el-table__body td.el-table__cell {
    padding: 0;
    .can_edit_cell:hover {
      color: #409eff !important;
    }
  }
  .cell {
    padding: 0;
    white-space: pre-wrap;
  }
  .padding012 .cell {
    padding: 0 12px !important;
  }
  td.el-table__cell .cell > :first-child {
    padding: 3px 12px;
  }

  .el-scrollbar__wrap {
    max-height: calc(100vh - 342px);
    overflow-y: scroll;
  }

  .seltAllbtnDis .cell {
    visibility: hidden;
  }
  .el-table__empty-block {
    height: 120px !important;
  }
}

:deep(.el-table--border th.bg-free) {
  background-color: rgb(239.8, 248.9, 235.3) !important;
}

// 红色标识
.c-red-font {
  background-color: #fef1f1 !important;
  span {
    // color: lightcoral;
    color: brown !important;
  }
}

// 绿色标识
.c-green {
  background: #55efc4 !important;
  span {
    color: #2f4f4f !important;
  }
}

.cellNumber:hover {
  text-decoration: underline;
}

.container {
  overflow: hidden; /* 超出部分隐藏 */
  white-space: nowrap; /* 防止文本换行 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>
